package com.itheima.mybatis.sqlsession.defaults;


import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.proxy.MapperProxy;
import com.itheima.mybatis.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * SqlSession接口的实现类
 */
public class DefultSqlSession  implements SqlSession {
    private Configuration cfg;
    private Connection connection;
    public DefultSqlSession(Configuration cfg){
        this.cfg=cfg;
        this.connection = DataSourceUtil.getConnection(cfg);
    }
    /**
     * 用于创建代理对象
     * @param daoIntrtfaceClass dao的接口字节码
     * @param <T>
     * @return
     */
    public <T> T getMapper(Class<T> daoIntrtfaceClass) {
        return (T)Proxy.newProxyInstance(daoIntrtfaceClass.getClassLoader(),
                new Class[]{daoIntrtfaceClass},
                new MapperProxy(cfg.getMappers(),connection)
                );

    }

    /**
     * 用于释放资源
     */
    public void close() {
        if (connection != null ) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
